package com.wrs.examsystem.util.MyShiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wrs.examsystem.entity.User;
import com.wrs.examsystem.service.UserService;
import com.wrs.examsystem.util.MyShiro.JWT.JWTToken;
import com.wrs.examsystem.util.MyShiro.JWT.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }


    //授权认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //登陆认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //这里用authenticationToken.getUsername也是可以的
        System.out.println("————Shiro身份认证开始————");
        String token = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null || !JWTUtil.verify(token, username)) {
            throw new AuthenticationException("token认证失败！");
        }
        QueryWrapper<User> selectByUsername = new QueryWrapper<>();
        selectByUsername.eq("username",username);

        User gcUser = userService.getOne(selectByUsername);
        if (gcUser == null) {
            throw new AuthenticationException("该用户不存在！");
        }
        return new SimpleAuthenticationInfo(token, token, "MyRealm");
    }
}

